package com.newer.weatherforecast.service;


import java.net.MalformedURLException;
import java.net.URL;

import com.newer.weatherforecast.dao.SmsDAO;
import com.newer.weatherforecast.entity.MyConfig;
import com.newer.weatherforecast.entity.SmsInfo;
import com.newer.weatherforecast.sms.SmsBroadCastReceiver;
import com.newer.weatherforecast.util.WeatherUtil;

import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.provider.ContactsContract;
import android.telephony.SmsManager;


public class SmsService extends Service {
	private SmsDAO smsDAO = null;
	private String userMsg = "";
	private String userNum = "";
	private String userName = "";
	private String return_result = "";
	private String receive_time = "";
	private String requestCity = "";
	private WeatherUtil weatherUtil = null;
	private SmsInfo sms = new SmsInfo();
	private MyConfig myConfig = null;
	public void onStart(Intent intent, int startId) {
		System.out.println("service");
		Bundle bundle = intent.getExtras();
		userMsg = (bundle.getString(SmsBroadCastReceiver.PARAM_MSG));
		userNum = (bundle.getString(SmsBroadCastReceiver.PARAM_DEST));
		userName = getContactPeople(userNum);
		myConfig = (MyConfig) (bundle.get("myConfig"));
		receive_time = bundle.getString("time");
		weatherUtil = new WeatherUtil();
		smsDAO = new SmsDAO(getApplicationContext());
		String KEY_WORD = myConfig.getKeyword();
		System.out.println(KEY_WORD);
		System.out.println(userMsg + userNum + userName);
		if (userMsg.contains(KEY_WORD)) {
			requestCity = userMsg.substring(userMsg.lastIndexOf("-") + 1);
			new MyThread().start();
		}
		super.onStart(intent, startId);
	}
	
	public void sendMsg(){
		while(weatherUtil.getCurrentWeather()==null){
			try {
				Thread.sleep(1000);
				System.out.println("网络问题，正在重新尝试");
				continue;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return_result = weatherUtil.getCurrentWeather().toString();
		System.out.println(return_result);
		PendingIntent sentIntent = 
			PendingIntent.getBroadcast(getApplicationContext(),
					0, new Intent(), PendingIntent.FLAG_ONE_SHOT);
		SmsManager sMan = SmsManager.getDefault();
		sMan.sendTextMessage
		(userNum, null,return_result, 
				sentIntent, null);
		if(myConfig.isAllow_save_msg()){
			saveMsg();
			Intent refreshList = new Intent("com.newer.list.doRefresh");
			sendBroadcast(refreshList);
		}
		System.out.println(sms);
		this.onDestroy();
	}
	public void saveMsg(){
		if(userName==null || userName.equals("")){
			sms.setSms_name(userNum);
		}else{
			sms.setSms_name(userName);
		}
		sms.setReturn_result(return_result);
		sms.setSms_body(userMsg);
		sms.setSms_num(userNum);
		sms.setReceive_time(receive_time);
		smsDAO.insertSmsInfo(sms);
	}
	private String getContactPeople(String incomingNumber)
	  {
	    ContentResolver contentResolver = getContentResolver();
	    Cursor cursor = null;
	    String[] projection = new String[]
	    { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
	        ContactsContract.CommonDataKinds.Phone.NUMBER };
	    cursor = contentResolver.query(
	        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
	        ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[]
	        { incomingNumber }, "");
	    if (cursor.getCount() == 0){
	    	return "";
	    } else if (cursor.getCount() > 0){
	      cursor.moveToFirst();
	      String name = cursor.getString(1);
	      return name;
	    	}
		return "";
	    }
	public IBinder onBind(Intent arg0) {
		return null;
	}
	class MyThread extends Thread{
    	public void run(){
    		Looper.prepare();
    		try {
    			URL url = new URL("http://www.google.com.hk/ig/api?hl=en&weather=" + requestCity);
    			weatherUtil.getCityWeather(url);
    			Thread.sleep(1000);
				sendMsg();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
}
